import { Request, Response } from 'express';
import { getRepository } from 'typeorm';
import { Word } from '../models/Word';
import { Category } from '../models/Category';
import { AuthRequest } from '../middlewares/auth';

// 获取单词列表
export const getWords = async (req: Request, res: Response) => {
  try {
    const { page = 1, limit = 10, categoryId, search } = req.query;
    const wordRepository = getRepository(Word);
    const queryBuilder = wordRepository.createQueryBuilder('word')
      .leftJoinAndSelect('word.category', 'category');

    if (categoryId) {
      queryBuilder.where('category.id = :categoryId', { categoryId });
    }

    if (search) {
      queryBuilder.andWhere('(word.word LIKE :search OR word.meaning LIKE :search)', {
        search: `%${search}%`
      });
    }

    const [words, total] = await queryBuilder
      .skip((Number(page) - 1) * Number(limit))
      .take(Number(limit))
      .getManyAndCount();

    res.json({
      words,
      total,
      page: Number(page),
      limit: Number(limit),
      totalPages: Math.ceil(total / Number(limit))
    });
  } catch (error) {
    res.status(500).json({ message: '获取单词列表失败', error: error.message });
  }
};

// 获取单个单词
export const getWord = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const wordRepository = getRepository(Word);
    const word = await wordRepository.findOne({
      where: { id: Number(id) },
      relations: ['category']
    });

    if (!word) {
      return res.status(404).json({ message: '单词不存在' });
    }

    res.json(word);
  } catch (error) {
    res.status(500).json({ message: '获取单词失败', error: error.message });
  }
};

// 创建单词
export const createWord = async (req: Request, res: Response) => {
  try {
    const { word, phonetic, meaning, example, synonym, antonym, difficulty, categoryId } = req.body;
    const wordRepository = getRepository(Word);
    const categoryRepository = getRepository(Category);

    const category = await categoryRepository.findOne({ where: { id: categoryId } });
    if (!category) {
      return res.status(404).json({ message: '分类不存在' });
    }

    const newWord = wordRepository.create({
      word,
      phonetic,
      meaning,
      example,
      synonym,
      antonym,
      difficulty,
      category
    });

    await wordRepository.save(newWord);
    res.status(201).json(newWord);
  } catch (error) {
    res.status(500).json({ message: '创建单词失败', error: error.message });
  }
};

// 更新单词
export const updateWord = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { word, phonetic, meaning, example, synonym, antonym, difficulty, categoryId } = req.body;
    const wordRepository = getRepository(Word);
    const categoryRepository = getRepository(Category);

    const existingWord = await wordRepository.findOne({ where: { id: Number(id) } });
    if (!existingWord) {
      return res.status(404).json({ message: '单词不存在' });
    }

    if (categoryId) {
      const category = await categoryRepository.findOne({ where: { id: categoryId } });
      if (!category) {
        return res.status(404).json({ message: '分类不存在' });
      }
      existingWord.category = category;
    }

    Object.assign(existingWord, {
      word,
      phonetic,
      meaning,
      example,
      synonym,
      antonym,
      difficulty
    });

    await wordRepository.save(existingWord);
    res.json(existingWord);
  } catch (error) {
    res.status(500).json({ message: '更新单词失败', error: error.message });
  }
};

// 删除单词
export const deleteWord = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const wordRepository = getRepository(Word);
    const word = await wordRepository.findOne({ where: { id: Number(id) } });

    if (!word) {
      return res.status(404).json({ message: '单词不存在' });
    }

    await wordRepository.remove(word);
    res.json({ message: '删除成功' });
  } catch (error) {
    res.status(500).json({ message: '删除单词失败', error: error.message });
  }
};

// 批量导入单词
export const importWords = async (req: Request, res: Response) => {
  try {
    const { words } = req.body;
    const wordRepository = getRepository(Word);
    const categoryRepository = getRepository(Category);

    const importedWords = [];
    for (const wordData of words) {
      const { word, phonetic, meaning, example, synonym, antonym, difficulty, categoryId } = wordData;
      
      const category = await categoryRepository.findOne({ where: { id: categoryId } });
      if (!category) {
        continue;
      }

      const newWord = wordRepository.create({
        word,
        phonetic,
        meaning,
        example,
        synonym,
        antonym,
        difficulty,
        category
      });

      await wordRepository.save(newWord);
      importedWords.push(newWord);
    }

    res.status(201).json({
      message: '导入成功',
      importedCount: importedWords.length
    });
  } catch (error) {
    res.status(500).json({ message: '导入单词失败', error: error.message });
  }
}; 